const express = require('express')
const router = express.Router()
const HotWord = require('../models/KeyWord')

router.get('/', async (req, res) => {
  const { word } = req.query
  if (word.trim().length) {
    const data = await HotWord.find({ name: new RegExp(word) }, '_id name')
    const exact = await HotWord.find({ name: word })
    if (exact.length === 1) {
      await HotWord.updateOne({ name: word }, { click: exact[0].click + 1 })
    } else {
      await HotWord.insertMany([{ name: word, click: 1 }])
    }

    if (data.length) {
      // 响应返回数据
      return res.json({
        code: 200,
        data: {
          suggests: data.slice(0, 10).filter(item => item.name !== word),
        },
      })
    }
  }

  res.json({
    code: 200,
    data: {
      suggests: [],
    },
  })
})

/**
 * 获取前12个热词
 */
router.get('/hotwords', (req, res) => {
  HotWord.find({}, '_id name')
    .limit(12)
    .sort('-click')
    .then(data => {
      res.json({
        code: 200,
        data: {
          list: data,
        },
      })
    })
})

module.exports = router
